/**
 * 
 */
package view;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import controller.Controls;

/**
 * Panel for adding new recipes to a database.
 * 
 * @author Andy
 */
public class AddRecipePanel extends JPanel
{
    /**
     * Serial Version ID
     */
    private static final long serialVersionUID = -8024913306338450668L;
    
    /**
     * Default item chosen for cuisines index.
     */
    private static final int DEFAULT_INDEX = 6;
    
    /**
     * The number of attributes in the Recipe database.
     */
    private static final int TOTAL_ATTRIBUTES = 14;
    
    /**
     * Attributes used for data entry.
     */
    private static final int USED_ATTRIBUTES = 14;
    
    /**
     * The position of the picture attribute.
     */
    private static final int PICTURE_ATTRIBUTE = 8;
   
    /**
     * The Difficulty attribute.
     */
    private static final int DIFFICULTY_ATTRIBUTE = 6;
    
    /**
     * Views attribute.
     */
    private static final int VIEWS_ATTRIBUTE = 7;
    
    /**
     * The cuisines attribute.
     */
    private static final int CUISINE_ATTRIBUTE = 5;
    
    /**
     * The course attribute.
     */
    private static final int COURSE_ATTRIBUTE = 2;
    
    /**
     * The title of the panel.
     */
    private static final String PANEL_TITLE = "Add a Recipe:  Enter recipe information below.";
    
    /**
     * Array that holds the labels needed to add a Recipe.
     */
    private static final String[] ATTRIBUTES = {"Recipe_ID", "Description", "Course", "Title", "author",
        "Cuisine", "Difficulty", "Number_of_Views", "Picture", "Notes",  "Prep_Time",
        "Serving_Size", "Cooking_Time"};
    
    /**
     * Modified text labels.
     */
    private static final String[] ATTRIBUTES2 = {"Recipe_ID", "Description", "Course", "Title", "author",
        "Cuisine", "Difficulty", "Number_of_Views", "Picture", "Notes",  "Prep Time in Minutes",
        "Serving Size", "Cooking Time in Minutes"};
    
    /**
     * List of Cuisines.
     */
    private static final String[] CUISINES = {"Mexican", "Italian","Chinese", "Japanese", "German",
        "Southern", "American", "Asian", "African", "Indian", "Thai", "French", "Spanish"};
    
    /**
     * Array of courses.
     */
    private static final String[] COURSES = {"side dish", "main dish", "appetizer", "dessert", "bread",
        "condiment", "salad", "beverage"};
    
    /**
     * The form for adding ingredients.
     */
    private final AddIngredientForm my_ingredients = new AddIngredientForm();
    
    /**
     * The array holding the steps.
     */
    private List<String> my_steps;
    
    /**
     * The combobox of cuisines.
     */
    private JComboBox<String> my_cuisines_list = new JComboBox<String>();
    
    /**
     * The combobox for courses.
     */
    private JComboBox<String> my_course_list = new JComboBox<String>();   
    
    /**
     * Array that holds the text boxes.
     */
    private JTextField[] my_input_boxes;
    
    /**
     * The picture text field.
     */
    private JTextField my_pic_path;
    
    /**
     * Holds the actual inputs from the text boxes.
     */
    private String[] my_inputs;
    
    /**
     * The list of ingredients.
     */
    private List<List<String>> my_ingredient_list = new ArrayList<List<String>>();
    
    /**
     * The button to fetch the picture.
     */
    private JButton my_picture_browse = new JButton("Browse");
    
    /**
     * The clear button.
     */
    private JButton my_clear;
    
    /**
     * Default radio button.
     */
    private JRadioButton my_button_1;
    
    private final Controls my_controller;

    /**
     * Constructor for the AddRecipePaneel.
     */
    public AddRecipePanel(Controls the_controller)
    {
       this.setLayout(new BorderLayout());
       prepareLists();
       makeForm();
       my_controller = the_controller;
       //this.setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50));

    }
    
    /**
     * Builds the form.
     */
    private void makeForm()
    {
        my_inputs = new String[TOTAL_ATTRIBUTES];
        my_inputs[TOTAL_ATTRIBUTES - 1] = "0";
        this.add(BorderLayout.NORTH, makeNorth());
        this.add(BorderLayout.CENTER, makeCenter());
        this.add(BorderLayout.SOUTH, makeSouth());
    }
    
    /**
     * Creates the North quadrant.
     * @return north
     */
    private JPanel makeNorth()
    {
       JPanel north = new JPanel();
       JLabel title = new JLabel(PANEL_TITLE);
       north.add(title);
        return north;
    }
    
    /**
     * Creates the Center quadrant.
     */
    private JPanel makeCenter()
    {
        my_input_boxes = new JTextField[TOTAL_ATTRIBUTES];
        JPanel center = new JPanel();
        my_pic_path = new JTextField();
        ButtonGroup difficulty_setting = new ButtonGroup();
        int diff_button_num = 4;
        center.setLayout(new GridLayout(TOTAL_ATTRIBUTES, 3));
        
        //The RecipeID which should not auto-chosen rather than user entered.
        my_input_boxes[0] = new JTextField();
        
        //Views attribute. By default views are 0.
        my_input_boxes[my_input_boxes.length - 1] = new JTextField("0");
        

        
        //Adds all text box entries except picture.
        for (int i = 1; i < USED_ATTRIBUTES; i++)
        {
            if (i == DIFFICULTY_ATTRIBUTE)
                {
                center.add(new JLabel(ATTRIBUTES2[i])); 
                JPanel buttons = new JPanel();
                my_button_1 = makeRadioButtons(1);
                difficulty_setting.add(my_button_1);
                buttons.add(my_button_1);
                for (int k = 2; k < diff_button_num; k++)
                  {
                    JRadioButton diff = (makeRadioButtons(k));
                    difficulty_setting.add(diff);
                    buttons.add(diff);       
                  }
                  center.add(buttons);
                  center.add(new JLabel());
                }
            else if (i == CUISINE_ATTRIBUTE)
            {
              my_input_boxes[i] = new JTextField();
              center.add(new JLabel(ATTRIBUTES2[i]));
              center.add(my_cuisines_list);
              center.add(new JLabel());
              my_cuisines_list.setSelectedIndex(DEFAULT_INDEX);
            }
            else if (i == COURSE_ATTRIBUTE)
            {
                my_input_boxes[i] = new JTextField();
                center.add(new JLabel(ATTRIBUTES2[i]));
                center.add(my_course_list);
                center.add(new JLabel());
                my_course_list.setSelectedIndex(0);
            }
            else if (i == PICTURE_ATTRIBUTE)
            {
                //Picture is a special case.  Picture has a button to go with it.  Added here.
                center.add(new JLabel(ATTRIBUTES2[PICTURE_ATTRIBUTE]));
                center.add(my_pic_path);
                center.add(my_picture_browse);
            }
            else if (i == VIEWS_ATTRIBUTE)
            {
                my_inputs[VIEWS_ATTRIBUTE] = 0 + "";
            }
            else
            {
              if (i < ATTRIBUTES2.length) {
              my_input_boxes[i] = new JTextField();
              center.add(new JLabel(ATTRIBUTES2[i]));
              center.add(my_input_boxes[i]);
              center.add(new JLabel());
              }
            }
        }
        
        JButton save = new JButton("Set Recipe");
        my_clear = new JButton("Clear");
        JButton cancel = new JButton("Cancel");
        center.add(save);
        center.add(my_clear);
        center.add(cancel);
        
        final Action save_action = new AbstractAction()
        {
          /**
             * Generated UID.
             */
            private static final long serialVersionUID = -8231877131952524605L;

        public void actionPerformed(final ActionEvent the_event)
          {
              my_input_boxes[CUISINE_ATTRIBUTE].setText((String) my_cuisines_list.getSelectedItem());
                
              my_input_boxes[COURSE_ATTRIBUTE].setText((String) my_course_list.getSelectedItem());
            //Saves all attributes to the my_inputs array.
              for (int i = 1; i < my_inputs.length; i++)
              {
                if(my_input_boxes[i] != null)
                    {
                      my_inputs[i] = my_input_boxes[i].getText();
                    }
              }
              my_inputs[PICTURE_ATTRIBUTE] = my_pic_path.getText();
              JOptionPane.showMessageDialog(null, "Recipe Set.  Now enter Ingrediants and steps below.  " +
                      "Press Done when finished.  Will not be saved until Done is pressed", "Recipe database", 1);
          }
        };
        save.addActionListener(save_action);
        
        final Action clear_action = new AbstractAction()
        {
          /**
             * Generated UID.
             */
            private static final long serialVersionUID = -4823559480766650016L;

        public void actionPerformed(final ActionEvent the_event)
          {
            for (int j = 0; j < my_input_boxes.length; j++)
            {
                if (my_input_boxes[j] != null)
                    {               
                      my_input_boxes[j].setText("");
                    }
                my_pic_path.setText("");
            }
            my_button_1.doClick();
            my_cuisines_list.setSelectedIndex(DEFAULT_INDEX);
            my_course_list.setSelectedIndex(0);
          }
        };
        my_clear.addActionListener(clear_action);
        
        final Action cancel_action = new AbstractAction()
        {

        /**
             * Generated UID.
             */
            private static final long serialVersionUID = 8259782139486054766L;

        public void actionPerformed(final ActionEvent the_event)
          {
            //Cancel action here.
          }
        };
        cancel.addActionListener(cancel_action);


        
        //Action for the browse picture button.
        final Action pic_action = new AbstractAction()
        {
          /**
             * Generated UID.
             */
            private static final long serialVersionUID = -8231877131952524605L;

        public void actionPerformed(final ActionEvent the_event)
          {
            JFileChooser browse = new JFileChooser();
            int selected = browse.showOpenDialog(AddRecipePanel.this);
            
            //Saves path of picture to text box.
            if (selected == JFileChooser.APPROVE_OPTION)
            {
              File file = browse.getSelectedFile();
              my_pic_path.setText(file.getPath());
            }
          }
        };
        my_picture_browse.addActionListener(pic_action);
        
        return center;
    }
    
    private JPanel makeSouth()
    {
        my_steps = new ArrayList<String>();
        JPanel south = new JPanel();
        JButton done = new JButton("Done");
        south.setLayout(new BorderLayout());
        JPanel south_center = my_ingredients;
        JPanel south_south = new JPanel();
        JPanel south_north = new JPanel();
        JLabel title = new JLabel("Enter Ingredients & steps.  Use buttons to add.");
        south_north.add(title);
        south_south.setLayout(new GridLayout(3, 3));
        
        JButton ingredient_add = new JButton("Add Ingredient");
        //south_south form.  Adds steps.
        final JTextField step = new JTextField();
        final JLabel step_label = new JLabel("Enter next step:");
        final JButton add_step = new JButton("Add Step");
        south_south.add(ingredient_add);
        south_south.add(new JLabel());
        south_south.add(new JLabel());
        south_south.add(step_label);
        south_south.add(step);
        south_south.add(add_step);
        south_south.add(done);
        south_south.add(new JLabel());
        south_south.add(new JLabel());
        
        //Adding the ingredient to the ArrayList.
        final Action ingredient_action = new AbstractAction()
        {

        /**
             * Generated UID.
             */
            private static final long serialVersionUID = 8944058413256734360L;

        public void actionPerformed(final ActionEvent the_event)
          {
            String[] input = my_ingredients.getInputs();
            ArrayList<String> inputs = new ArrayList<String>();
            for (int i = 0; i < input.length; i++)
            {
                inputs.add(input[i]);
            }
            my_ingredient_list.add(inputs);
          }
        };
        ingredient_add.addActionListener(ingredient_action);
        
        //Adding the steps to its own array list.
        final Action step_action = new AbstractAction()
        {

        /**
             * Generated UID.
             */
            private static final long serialVersionUID = 8944058413256734360L;

        public void actionPerformed(final ActionEvent the_event)
          {
            my_steps.add(step.getText());
            step.setText("");
          }
        };
        add_step.addActionListener(step_action);
        
        final Action done_action = new AbstractAction()
        {

        /**
             * Generated UID.
             */
            private static final long serialVersionUID = 4274265974674030892L;

        public void actionPerformed(final ActionEvent the_event)
          {
            sendData();
          }
        };
        done.addActionListener(done_action);
        
        south.add(BorderLayout.NORTH, south_north);
        south.add(BorderLayout.CENTER, south_center);
        south.add(BorderLayout.SOUTH, south_south);
        
        return south;
    }

    
    /**
     * Sets up the lists used by the form.
     */
    private void prepareLists()
    {
        for (int r = 0; r < CUISINES.length; r++)
        {
            my_cuisines_list.addItem(CUISINES[r]);
        }
        
        for (int i = 0; i < COURSES.length; i++)
        {
            my_course_list.addItem(COURSES[i]);
        }
    }
    
    private JRadioButton makeRadioButtons(final int the_difficulty)
    {
        
        final String difficulty;
        if (the_difficulty == 1)
        {
            difficulty = "Easy";
        }
        else if (the_difficulty == 2)
        {
            difficulty = "Intermediate";
        }
        else
        {
            difficulty = "Hard";
        }
        JRadioButton difficulty_button = new JRadioButton(difficulty);
        
        final Action button_action = new AbstractAction()
        {

        /**
             * Generated UID.
             */
            private static final long serialVersionUID = -4236802325258823505L;

        public void actionPerformed(final ActionEvent the_event)
          {
            my_inputs[DIFFICULTY_ATTRIBUTE] = difficulty;
          }
        };
        difficulty_button.addActionListener(button_action);
        
        return difficulty_button;
    }
    
    /**
     * Use as needed.
     */
    private void sendData()
    {
        //All data is ready.
        //All user inputs are saved in the "my_inputs" String array.
        ArrayList<String> results = new ArrayList<String>();
        for (int formatter = 1; formatter < ATTRIBUTES.length; formatter++)
        {
            results.add(ATTRIBUTES[formatter]);
            results.add(my_inputs[formatter]);
        }
        
        my_controller.addRecipe(results, my_ingredient_list, my_steps);
    }
    
        
    /**
     * Returns the saved attributes.
     * @return my_inputs.
     */
    public String[] getAttributes()
    {
        return my_inputs;
    }
    
}
